package org.microsites.domain.dao.eod;

import java.util.ArrayList;
import java.util.List;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.DataSet;
import net.lemnik.eodsql.GeneratedKeys;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.DeploymentDAO;
import org.microsites.domain.model.Deployment;
import org.microsites.util.EodDaoSupport;

public class DeploymentDAOImpl extends EodDaoSupport implements DeploymentDAO {
	private Query query;
	
	@Override
	public void create(Deployment entity) {
		entity.setId(getQuery().create(entity));
	}

	@Override
	public void delete(Long id) {
		getQuery().delete(id);
	}

	@Override
	public List<Deployment> list() {
		return getQuery().list();
	}

	@Override
	public List<Deployment> sublist(Long id) {
		return id == null ? new ArrayList<Deployment>() : getQuery().sublist(id);
	}

	@Override
	public Deployment load(Long id) {
		return getQuery().load(id);
	}

	@Override
	public void update(Deployment entity) {
		getQuery().update(entity);
	}
	
	public Query getQuery() {
		return query == null ? query = super.getQuery(Query.class) : query;
	}

	@Override
	public List<String> autocomplete(String column, String pattern) {
		return super.select(String.class, "SELECT " + column + " FROM Deployment WHERE " + column + " LIKE ?1 GROUP BY " + column, '%' + pattern + '%');
	}
	
	static interface Query extends BaseQuery {
		
		@Select(sql = "SELECT * FROM Deployment")
		public DataSet<Deployment> list();
		
		@Select(sql = "SELECT * FROM Deployment WHERE server=?1")
		public DataSet<Deployment> sublist(Long id);

		@Select(sql = "SELECT * FROM Deployment WHERE id=?1")
		public Deployment load(Long id);

        @Update(sql = "INSERT INTO Deployment (name,description,server,[database],project,admin,code) " +
        		"VALUES (?{1.name},?{1.description},?{1.server},?{1.database},?{1.project},?{1.admin},?{1.code})",
                keys = GeneratedKeys.RETURNED_KEYS_FIRST_COLUMN)
		public Long create(Deployment d);
		
        @Update(sql = "UPDATE Deployment SET name=?{1.name},description=?{1.description},server=?{1.server}," +
        		"[database]=?{1.database},project=?{1.project},admin=?{1.admin},code=?{1.code} WHERE id=?{1.id}")
		public void update(Deployment d);
		
		@Update(sql = "DELETE FROM Deployment WHERE id=?1")
		public void delete(Long id);
	}	
}
